package com.dyh.lvup.byteBuddy;

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.MethodDelegation;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;

/*
@Author=Joey Wheeler
@Date=2021/3/1 16:57
*/
public class Delegation {


    /*
    *
    * HelloWorld#hello =>SayHello#hello
    *
    *
    *   .method (ture) 匹配方法
    *   .defineMethod 新方法
    * */

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        DynamicType.Unloaded<?> dynamicType = new ByteBuddy()
                .subclass(Object.class)
                .name("com.dyh.lvup.byteBuddy.HelloWorld")
                .defineMethod("hello", void.class, Modifier.PUBLIC + Modifier.STATIC)
                .withParameter(String[].class, "args")
                /*SayHello 函数定义必须完全一致*/
                .intercept(MethodDelegation.to(SayHello.class))
                .make();

        Class<?> clazz = dynamicType.load(Delegation.class.getClassLoader())
                .getLoaded();


        clazz.getMethod("hello", String[].class).invoke(clazz.newInstance(), (Object) new String[1]);
    }
}
